<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>进度条</title>
    <script src="lib/jquery.js"></script>
    <link rel="stylesheet" href="lib/bootstrap.css">
</head>
<body>
<input type="file" id="file1">
<button id="btnFile">上传文件</button>
<br>
<img src="" alt="" id="img" width="800">
<div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
        0%
    </div>
</div>
<script>
    var btnFile = document.querySelector("#btnFile");
    btnFile.addEventListener('click', () => {
            let file = document.querySelector('#file1').files;
            if (file.length <= 0) {
                return alert('请选择你需要上传的文件')
            }
            var fd = new FormData();
            fd.append('avatar', file[0])
            var xhr = new XMLHttpRequest();
            xhr.upload.onprogress = (e) => {
                if (e.lengthComputable) {
                    var percentComplete = Math.ceil((e.loaded / e.total) * 100)
                    $('#percent').attr('style', 'width: ' + percentComplete + '%;').html(percentComplete + '%')
                }
            }
            xhr.upload.onload = function () {
                $('#percent').removeClass().addClass('progress-bar progress-bar-success')
            }
            xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
            xhr.send(fd);
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText);
                    console.log(data)
                    if (data.status === 200) {
                        document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url;
                    } else {
                        console.log('上传失败')
                    }
                }
            }
        }
    )
</script>
</body>
</html>
